<template>
  <page-container title="数据处理规则管理">
    <div class="data-transform-list">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openEditDialog()">新增处理规则</el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="请输入规则名称"
          clearable
          @clear="handleSearch"
          style="width: 250px; margin-left: 10px"
          @keyup.native.enter="handleSearch"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        :fit="true"
        :border="true"
        v-loading="loading"
        header-height="50"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="collectConfigId" label="采集配置ID" min-width="100">
          <template slot-scope="{ row }">
            <el-tag>{{ row.collectConfigId }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceField" label="源字段" min-width="120" />
        <el-table-column prop="targetField" label="目标字段" min-width="120" />
        <el-table-column prop="transformType" label="转换类型" min-width="120">
          <template slot-scope="{ row }">
            <el-tag>{{ row.transformType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="transformRule" label="转换规则" show-overflow-tooltip min-width="200">
          <template slot-scope="{ row }">
            <el-tooltip effect="dark" :content="row.transformRule" placement="top">
              <span>{{ (row.transformRule || '').length > 30 ? (row.transformRule.slice(0, 30) + '...') : (row.transformRule || '') }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handlePreview(scope.row)">预览</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="600px"
        @close="resetForm"
      >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="关联采集配置" prop="collectConfigId">
            <el-select
              v-model="form.collectConfigId"
              placeholder="请选择采集配置"
              style="width: 100%"
            >
              <el-option
                v-for="item in collectConfigOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="源字段" prop="sourceField">
            <el-input v-model="form.sourceField" placeholder="例如: user_name" />
          </el-form-item>
          <el-form-item label="目标字段" prop="targetField">
            <el-input v-model="form.targetField" placeholder="例如: username" />
          </el-form-item>
          <el-form-item label="转换类型" prop="transformType">
            <el-select
              v-model="form.transformType"
              placeholder="请选择类型"
              @change="handleTransformTypeChange"
            >
              <el-option
                v-for="item in transformTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 动态规则输入 -->
          <template v-if="form.transformType">
            <el-form-item
              v-if="form.transformType === 'string_to_date'"
              label="日期格式"
              prop="transformRule"
            >
              <el-input v-model="form.transformRule" placeholder="例如: yyyy-MM-dd" />
            </el-form-item>
            <el-form-item
              v-if="form.transformType === 'regex_replace'"
              label="正则表达式"
              prop="transformRule"
            >
              <el-input v-model="form.transformRule.pattern" placeholder="输入正则模式" />
              <el-input
                v-model="form.transformRule.replacement"
                placeholder="输入替换内容"
                style="margin-top: 10px"
              />
            </el-form-item>
            <el-form-item
              v-if="form.transformType === 'default_value'"
              label="默认值"
              prop="transformRule"
            >
              <el-input v-model="form.transformRule" />
            </el-form-item>
          </template>
          <el-form-item label="字段顺序" prop="sortOrder">
            <el-input-number v-model="form.sortOrder" :min="1" />
          </el-form-item>
          <el-form-item label="处理脚本" prop="script" v-if="form.transformType === 'script'">
            <el-input v-model="form.script" type="textarea" :rows="4" placeholder="输入JS处理脚本" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </page-container>
</template>

<script>
import PageContainer from '@/components/PageContainer.vue'
import {
  getTransformRuleList,
  deleteTransformRule,
  addTransformRule,
  updateTransformRule,
  getTransformTypeList,
  getTransformRuleTypes,
  previewTransformRule
} from '@/api/transform'
import { getDataCollectConfigList } from '@/api/collection'

export default {
  name: 'DataTransformList',
  components: {
    PageContainer
  },
  data () {
    return {
      tableData: [],
      loading: false,
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增处理规则',
      submitLoading: false,
      form: {
        id: null,
        collectConfigId: null,
        sourceField: '',
        targetField: '',
        transformType: '',
        transformRule: '',
        sortOrder: 1,
        script: ''
      },
      collectConfigOptions: [],
      transformTypeOptions: [],
      rules: {
        collectConfigId: [{ required: true, message: '请选择采集配置', trigger: 'change' }],
        sourceField: [{ required: true, message: '请输入源字段', trigger: 'blur' }],
        targetField: [{ required: true, message: '请输入目标字段', trigger: 'blur' }],
        transformType: [{ required: true, message: '请选择转换类型', trigger: 'change' }]
      }
    }
  },
  mounted () {
    this.loadData()
    this.loadCollectConfigOptions()
    this.loadTransformTypeOptions()
  },
  methods: {
    // 加载数据
    async loadData () {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          searchId: this.searchId || undefined
        }
        const res = await getTransformRuleList(params)
        console.log('res', res)
        this.tableData = res.data.records || []
        this.total = res.data.total || 0
      } catch (e) {
        this.$message.error('加载失败: ' + (e.message || e))
      } finally {
        this.loading = false
      }
    },
    // 删除规则
    async handleDelete (row) {
      try {
        await this.$confirm('确认删除该规则？', '提示', { type: 'warning' })
        const res = await deleteTransformRule(row.id)
        console.log('res删除结果', res)
        this.$message.success('删除成功')
        this.loadData()
      } catch (e) {
        if (e !== 'cancel') {
          this.$message.error('删除失败: ' + (e.message || e))
        }
      }
    },
    // 打开编辑弹窗
    openEditDialog (row) {
      if (row) {
        this.dialogTitle = '编辑处理规则'
        this.form = { ...row }
        if (row.transformType === 'regex_replace' && typeof row.transformRule === 'string') {
          try {
            this.form.transformRule = JSON.parse(row.transformRule)
          } catch (e) {
            this.form.transformRule = { pattern: '', replacement: '' }
          }
        }
      } else {
        this.dialogTitle = '新增处理规则'
        this.resetForm()
      }
      this.dialogVisible = true
    },
    resetForm () {
      this.$nextTick(() => {
        if (this.$refs.formRef) this.$refs.formRef.resetFields()
      })
      this.form = {
        id: null,
        collectConfigId: null,
        sourceField: '',
        targetField: '',
        transformType: '',
        transformRule: '',
        sortOrder: 1,
        script: ''
      }
    },
    handleTransformTypeChange () {
      this.form.transformRule = ''
      if (this.form.transformType === 'regex_replace') {
        this.form.transformRule = { pattern: '', replacement: '' }
      }
    },
    async handleSubmit () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          const submitData = { ...this.form }
          if (submitData.transformType === 'regex_replace') {
            submitData.transformRule = JSON.stringify(submitData.transformRule)
          }
          if (submitData.id) {
            await updateTransformRule(submitData)
            this.$message.success('编辑成功')
          } else {
            await addTransformRule(submitData)
            this.$message.success('新增成功')
          }
          this.dialogVisible = false
          this.loadData()
        } catch (e) {
          this.$message.error('保存失败: ' + (e.message || e))
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 分页切换
    handleCurrentChange (page) {
      this.currentPage = page
      this.loadData()
    },
    // pageSize切换
    handleSizeChange (size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadData()
    },
    // 搜索
    handleSearch () {
      this.currentPage = 1
      this.loadData()
    },
    async loadCollectConfigOptions () {
      const res = await getDataCollectConfigList({ page: 1, pageSize: 100 })
      console.log('res数据采集配置', res)
      this.collectConfigOptions = res.data ? (res.data.records || res.data) : []
    },
    async loadTransformTypeOptions () {
      try {
        // 优先使用新的API获取类型
        const res = await getTransformRuleTypes()
        console.log('res数据处理类型', res)
        if (Array.isArray(res.data)) {
          this.transformTypeOptions = res.data.map(type => ({
            label: type,
            value: type
          }))
        } else {
          // 如果新API失败，尝试旧API
          const oldRes = await getTransformTypeList()
          if (Array.isArray(oldRes.data)) {
            this.transformTypeOptions = oldRes.data.map(type => ({
              label: type,
              value: type
            }))
          } else {
            // 使用默认值
            this.transformTypeOptions = [
              { label: '字符串转日期', value: 'string_to_date' },
              { label: '正则替换', value: 'regex_replace' },
              { label: '默认值填充', value: 'default_value' },
              { label: '类型转换', value: 'type_cast' },
              { label: '脚本处理', value: 'script' }
            ]
          }
        }
      } catch (e) {
        console.error('获取转换类型失败:', e)
        this.$message.error('获取数据处理类型失败: ' + (e.message || e))
        // 使用默认值
        this.transformTypeOptions = [
          { label: '字符串转日期', value: 'string_to_date' },
          { label: '正则替换', value: 'regex_replace' },
          { label: '默认值填充', value: 'default_value' },
          { label: '类型转换', value: 'type_cast' },
          { label: '脚本处理', value: 'script' }
        ]
      }
    },
    async handlePreview (row) {
      try {
        const res = await previewTransformRule(row.id)
        console.log('res预览结果', res)
        this.$message.success('预览成功')
        // 可以在这里添加预览数据的展示逻辑，比如打开一个预览弹窗
        this.$notify({
          title: '预览结果',
          message: JSON.stringify(res.data, null, 2),
          duration: 0,
          type: 'success'
        })
      } catch (e) {
        this.$message.error('预览失败: ' + (e.message || e))
      }
    },
    handleEdit (row) {
      this.openEditDialog(row)
    }
  }
}
</script>

<style scoped>
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: end;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.el-table th{
  vertical-align: middle;
  line-height: 60px;
}
.data-transform-list {
  width: 100%;
  padding: 0;
  margin: 0;
}
.data-transform-list >>> .el-table th {
  height: 100px;
  line-height: 100px;
  vertical-align: middle;
  padding: 0;
}
</style>
